<!-- eslint-disable vue/multi-word-component-names -->
<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/login' // 导入登录API
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus' // 导入消息提示组件

const router = useRouter()
const userStore = useUserStore()
const captcha = ref('')
const formData = ref({
  account: '',
  password: '',
  captcha: '',
  agreement: true
})

function generateCaptcha() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captcha.value = result
  return result
}

// 刷新验证码
function refreshCaptcha() {
  generateCaptcha()
  const captchaEl = document.getElementById('captchaImg')
  captchaEl.classList.add('refresh-animation')
  setTimeout(() => {
    captchaEl.classList.remove('refresh-animation')
  }, 300)
}

const handleSubmit = async (e) => {
  e.preventDefault()

  // 前端验证码校验
  if (formData.value.captcha.toLowerCase() !== captcha.value.toLowerCase()) {
    ElMessage.error('验证码错误，请重新输入')
    refreshCaptcha()
    return
  }

  try {
    // 调用登录接口
    const response = await login({
      account: formData.value.account,
      password: formData.value.password
    })

    // 处理接口响应
    if (response.code === 0) { // 假设0为成功状态码
      const { userInfoVO } = response.data

      // 存储Token和用户角色
      localStorage.setItem('token', userInfoVO.token)
      // 从用户信息中获取角色（根据后端返回结构调整）
      const userRole = userInfoVO.roleName || 'admin'
      localStorage.setItem('userRole', userRole)

      // 更新Pinia状态
      userStore.login(userInfoVO.token, userRole)

      // 获取跳转参数，如果有则跳转到原页面，否则跳首页
      const redirectPath = router.currentRoute.value.query.redirect || '/'
      router.push(redirectPath)
      ElMessage.success('登录成功')
    } else {
      // 显示后端返回的错误信息
      ElMessage.error(response.msg || '登录失败，请重试')
      refreshCaptcha() // 刷新验证码
    }
  } catch (error) {
    // 处理网络错误或异常
    console.error('登录请求失败:', error)
    ElMessage.error('网络异常，请检查连接后重试')
    refreshCaptcha() // 刷新验证码
  }
}


onMounted(() => {
  generateCaptcha()
})
</script>

<template>
  <div class="login-page">
    <div class="login-bg"></div>
    <div class="login-gradient"></div>
    <div class="page-content">
      <div class="login-container">
        <div class="login-box">
          <div class="login-header">
            <div class="logo">
              <i class="el-icon-user"></i>
              <h1>系统登录</h1>
            </div>
            <p class="slogan">欢迎使用本系统，请登录以继续</p>
          </div>
          <form class="login-form" @submit="handleSubmit">
            <div class="form-group">
              <div class="input-wrapper">
                <i class="el-icon-user"></i>
                <input type="text" v-model="formData.account" placeholder="请输入账号" required />
              </div>
            </div>
            <div class="form-group">
              <div class="input-wrapper">
                <i class="el-icon-lock"></i>
                <input type="password" v-model="formData.password" placeholder="请输入密码" required />
              </div>
            </div>
            <div class="form-group captcha-group">
              <div class="input-wrapper captcha-input">
                <input type="text" v-model="formData.captcha" placeholder="请输入验证码" required />
              </div>
              <div id="captchaImg" class="captcha-img" @click="refreshCaptcha">
                {{ captcha }}
              </div>
            </div>
            <div class="agreement-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="formData.agreement" />
                <span class="checkmark"></span>
                <span class="text">我已阅读并同意相关服务条款</span>
              </label>
            </div>
            <button type="submit" class="btn-login">
              登录
            </button>
          </form>
          <div class="register-link">
            还没有账号？<a href="/register">立即注册</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 背景样式优化 */
.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('https://picsum.photos/id/1/1920/1080') no-repeat center center;
  background-size: cover;
  z-index: 1;
  filter: brightness(0.65);
  transform: scale(1.02);
  animation: bgZoom 20s infinite alternate;
}

.login-gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(22, 38, 54, 0.92) 0%, rgba(22, 38, 54, 0.75) 100%);
  z-index: 2;
}

/* 添加背景缩放动画 */
@keyframes bgZoom {
  from { transform: scale(1.02); }
  to { transform: scale(1.08); }
}

/* 页面内容容器 - 确保在各种屏幕尺寸下完全居中 */
.page-content {
  position: relative;
  z-index: 3;
  width: 100%;
  max-width: 1200px;
  padding: 20px;
}

/* 登录容器优化 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 40px);
}

/* 登录框美化 */
.login-box {
  width: 100%;
  max-width: 420px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
  padding: 50px 35px;
  transform: translateY(0);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  overflow: hidden;
}

/* 登录框顶部装饰 */
.login-box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5px;
  background: linear-gradient(90deg, #27ba9b, #36d1b3);
}

.login-box:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 45px rgba(0, 0, 0, 0.3);
}

/* 登录标题优化 */
.login-header {
  text-align: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 15px;
}

.logo i {
  font-size: 32px;
  color: #27ba9b;
  transition: transform 0.3s ease;
}

.login-box:hover .logo i {
  transform: scale(1.15) rotate(5deg);
}

.logo h1 {
  font-size: 26px;
  font-weight: 700;
  color: #162636;
  margin: 0;
  letter-spacing: 0.5px;
}

.slogan {
  color: #666;
  font-size: 15px;
  margin: 0;
  letter-spacing: 0.3px;
}

/* 表单样式优化 */
.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 22px;
}

.input-wrapper {
  position: relative;
  width: 100%;
}

.input-wrapper i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
  font-size: 18px;
  transition: color 0.3s ease;
}

.input-wrapper input:focus + i {
  color: #27ba9b;
}

.input-wrapper input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 1px solid #ddd;
  border-radius: 10px;
  font-size: 15px;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.input-wrapper input:focus {
  border-color: #27ba9b;
  box-shadow: 0 0 0 4px rgba(39, 186, 155, 0.12);
  outline: none;
  background-color: #fff;
}

.input-wrapper input::placeholder {
  color: #bbb;
}

/* 验证码区域优化 */
.captcha-group {
  display: flex;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-img {
  width: 130px;
  height: 50px;
  border: 1px solid #ddd;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 20px;
  letter-spacing: 4px;
  background-color: #f9f9f9;
  user-select: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

/* 更复杂的验证码干扰效果 */
.captcha-img::before,
.captcha-img::after,
.captcha-img span::before,
.captcha-img span::after {
  content: '';
  position: absolute;
  background-color: rgba(0, 0, 0, 0.1);
}

.captcha-img::before {
  width: 100%;
  height: 2px;
  transform: rotate(-18deg);
}

.captcha-img::after {
  width: 100%;
  height: 2px;
  transform: rotate(12deg);
}

.captcha-img span::before {
  width: 2px;
  height: 100%;
  transform: rotate(30deg);
}

.captcha-img span::after {
  width: 2px;
  height: 100%;
  transform: rotate(-25deg);
}

.captcha-img:hover {
  border-color: #27ba9b;
  background-color: #f0f9f7;
}

.refresh-animation {
  animation: shake 0.4s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
}

@keyframes shake {
  10%, 90% { transform: translateX(-2px); }
  20%, 80% { transform: translateX(4px); }
  30%, 50%, 70% { transform: translateX(-6px); }
  40%, 60% { transform: translateX(6px); }
}

/* 协议勾选框优化 */
.agreement-group {
  margin-bottom: 30px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 13px;
  color: #666;
}

.checkbox-label input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: relative;
  height: 16px;
  width: 16px;
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-right: 8px;
  transition: all 0.2s ease;
}

.checkbox-label input:checked ~ .checkmark {
  background-color: #27ba9b;
  border-color: #27ba9b;
  animation: checkmark 0.2s ease;
}

@keyframes checkmark {
  from { transform: scale(0.8); }
  to { transform: scale(1); }
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
  left: 5px;
  top: 1px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-label input:checked ~ .checkmark:after {
  display: block;
}

.checkbox-label .text {
  transition: color 0.2s ease;
}

.checkbox-label:hover .text {
  color: #27ba9b;
}

/* 登录按钮优化 */
.btn-login {
  width: 100%;
  padding: 15px;
  background-color: #27ba9b;
  color: #fff;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
  overflow: hidden;
}

/* 按钮悬停效果 */
.btn-login::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: all 0.6s ease;
}

.btn-login:hover::before {
  left: 100%;
}

.btn-login:hover {
  background-color: #21a68b;
  box-shadow: 0 6px 16px rgba(39, 186, 155, 0.4);
  transform: translateY(-2px);
}

.btn-login:active {
  transform: translateY(0);
  box-shadow: 0 3px 8px rgba(39, 186, 155, 0.3);
}

/* 注册链接优化 */
.register-link {
  text-align: center;
  margin-top: 25px;
  font-size: 14px;
  color: #666;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.register-link a {
  color: #27ba9b;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.2s ease;
  position: relative;
  padding-bottom: 2px;
}

.register-link a::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 1px;
  background-color: #27ba9b;
  transition: width 0.3s ease;
}

.register-link a:hover {
  color: #21a68b;
}

.register-link a:hover::after {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-box {
    padding: 40px 25px;
    max-width: 90vw;
  }

  .captcha-img {
    width: 110px;
  }

  .logo h1 {
    font-size: 24px;
  }
}

@media (max-height: 600px) {
  .login-container {
    min-height: auto;
    padding: 40px 0;
  }
}
</style>
